<?php

/**
 * Description of Form
 *
 * @author user3
 */
class Bluembo_Form extends Zend_Form {

    /**
     * @var Zend_Controller_Request_Http
     */
    protected $_request;

    /**
     *
     * @var Zend_Controller_Action_Helper_Url
     */
    protected $_url;
    protected $_isEdit = false;

    function __construct($options = null)
    {
        $this->_request = Zend_Controller_Front::getInstance()->getRequest();
        $this->_url = Zend_Controller_Action_HelperBroker::getStaticHelper('Url');
        parent::__construct($options);

        if (!isset($options['edit'])) {
            $this->setEdit($this->_isEdit());
        }

        $this->_setDefaultsData();
    }

    protected function _setDefaultsData()
    {
        if ($this->_isEdit) {
            $table = $this->_getEditTable();
            if (!$table) {
                return false;
            }
            $select = $table->select()->where("id=?", $this->_request->getParam('id'));
            $row    = $table->fetchRow($select);
            if ($row) {
                $this->setDefaults($row->toArray());
                return true;
            }
        }
        return false;
    }

    public function setEdit($value)
    {
        $this->_isEdit = $value;
    }

    protected function _isEdit()
    {
        return $this->_request->getParam('id') != null;
    }

    public function saveData($data = null)
    {
        if (!$this->_getEditTable()) {
            throw new Exception("No table editing ...");
        }
        
        if (!$data) {
            $data = $this->getValues();
        }

        if ($this->_isEdit) {
            return $this->_update($data);
        } else {
            return $this->_insert($data);
        }
    }
    
    public function getValues(){
        $data = parent::getValues();
        foreach($this->getElements() as $key=>$element){
            if($element instanceof Form_Element_Free){
                unset($data[$key]);
            }
        }
        return $data;
    }

    protected function _insert($data)
    {
        $row = $this->_getEditTable()->createRow();
        return $row->setFromArray($data)->save();
    }

    protected function _update($data)
    {
        $table = $this->_getEditTable();
        $row   = $table->fetchRow($table->select()->where("id=?", $this->_request->getParam('id')));
        if ($row) {
            return $row->setFromArray($data)->save();
        } else {
            throw new Exception("Row not found ...");
        }
    }    

    /**
     *
     * @return Zend_Db_Table_Abstract
     */
    protected function _getEditTable()
    {
        return null;
    }

}